package matcher

import (
	"encoding/xml"
	"fmt"
	"regexp"
	"strings"
	"titargo/resource"
)

type AtagMatcher struct {
	atagRegExp *regexp.Regexp
	strs       []*resource.Link
}

func (m *AtagMatcher) SetString(str string) {
	atag := m.atagRegExp.FindAllString(str, -1)
	for _, a := range atag {
		href, content := getHref(a)
		if strings.Contains(href, "javascript") || strings.Contains(href, "#") || strings.Contains(href, "+") {
			continue
		}
		if strings.EqualFold(href, "") {
			fmt.Println(href)
			continue
		}
		if strings.Index(href, "http://") != 0 && strings.Index(href, "https://") != 0 {
			href = Baseurl + href
			fmt.Println(href)
		}
		link := &resource.Link{Href: href, Content: content}
		m.strs = append(m.strs, link)
	}
}

func (m AtagMatcher) GetAttr() []*resource.Link {
	return m.strs
}

func getHref(tag string) (href, content string) {
	inputReader := strings.NewReader(tag)
	decoder := xml.NewDecoder(inputReader)
	for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
		switch token := t.(type) {
		case xml.StartElement:
			for _, attr := range token.Attr {
				attrName := attr.Name.Local
				attrValue := attr.Value
				if strings.EqualFold(attrName, "href") || strings.EqualFold(attrName, "HREF") {
					href = attrValue
				}
			}
		case xml.EndElement:
		case xml.CharData:
			content = string([]byte(token))
		default:
			href = ""
			content = ""
		}
	}
	return href, content
}

func NewAtagMatcher() *AtagMatcher {
	m := &AtagMatcher{}
	m.atagRegExp = regexp.MustCompile(`<a[^>]+[(href)|(HREF)]\s*\t*\n*=\s*\t*\n*[(".+")|('.+')][^>]*>[^<]*</a>`)
	return m
}
